"""
Case Type   : 多节点写入
Case Name   : 备机非事务下执行set语句
Create At   : 2023/1/9
Owner       : @li-xin12345
Description :
    1.修改enable_remote_execute参数值为on
    2.备机非事务下执行set语句，不满足10条set语句且没有写语句，查看日志
    3.备机非事务下执行10条set语句，查看日志
    4.执行set语句和1条写语句，查看日志
    5.环境清理，恢复参数
Expect      :
    1.修改成功
    2.不建立连接
    3.建立连接，并转发给主机
    4.建立连接，并转发给主机
    5.环境清理成功，恢复参数成功
History     :
    Modified by @li-xin12345 2023/3/15:研发代码变更，libpqsw日志打印增加线程号，优化断言以适配新代码
    Modified by @kyeleze 2023/7/5:研发代码变更，日志打印信息更改，优化断言以适配新代码
"""
import os
import time
import unittest
from yat.test import Node
from yat.test import macro
from testcase.utils.Logger import Logger
from testcase.utils.Common import Common
from testcase.utils.CommonSH import CommonSH
from testcase.utils.Constant import Constant

PrimarySh = CommonSH('PrimaryDbUser')


@unittest.skipIf(1 == PrimarySh.get_node_num(),
                 'Single node, and subsequent codes are not executed.')
class MultiNodeWrite(unittest.TestCase):
    def setUp(self):
        self.logger = Logger()
        self.logger.info(f"-----{os.path.basename(__file__)} start-----")
        self.standby_node = Node('Standby1DbUser')
        self.standby_sh = CommonSH('Standby1DbUser')
        self.constant = Constant()
        self.common = Common('Standby1DbUser')
        self.table_name = 't_multi_node_write_0036'
        self.new_log_path = os.path.join(macro.PG_LOG_PATH,
                                         'pg_log_multi_node_write_case0034')
        self.enable_remote_execute = 'enable_remote_execute'
        self.log_statement = 'log_statement'
        self.log_directory = 'log_directory'
        self.remote_execute_default = self.common.show_param(
            self.enable_remote_execute)
        self.log_statement_default = self.common.show_param(self.log_statement)
        self.log_dir_default = self.common.show_param(self.log_directory)
        shell_cmd = f"rm -rf {self.new_log_path}"
        self.logger.info(shell_cmd)
        shell_msg = self.common.get_sh_result(self.standby_node, shell_cmd)
        self.assertEquals('', shell_msg, '删除目录失败')

    def test_multi_node_write(self):
        step1 = "-----step1:修改enable_remote_execute参数值为on;expect:修改成功-----"
        self.logger.info(step1)
        result = self.standby_sh.execute_gsguc(
            'set', self.constant.GSGUC_SUCCESS_MSG,
            f'{self.enable_remote_execute}=on')
        self.assertTrue(result, '执行失败' + step1)
        restart_res = self.standby_sh.restart_db_cluster()
        self.assertTrue(restart_res, '执行失败' + step1)
        show_remote_execute = self.common.show_param(self.enable_remote_execute)
        self.assertEquals(show_remote_execute, 'on', '执行失败' + step1)
        result = self.standby_sh.execute_gsguc('reload',
                                               self.constant.GSGUC_SUCCESS_MSG,
                                               f'{self.log_statement}=all')
        self.assertTrue(result, '执行失败' + step1)
        result = self.standby_sh.execute_gsguc(
            'reload', self.constant.GSGUC_SUCCESS_MSG,
            f'{self.log_directory}=\'{self.new_log_path}\'', single=True)
        self.assertTrue(result, '执行失败' + step1)
        show_log_statement = self.common.show_param(self.log_statement)
        self.assertEquals(show_log_statement, 'all', '执行失败' + step1)
        show_log_directory = self.common.show_param(self.log_directory)
        self.assertEquals(show_log_directory, self.new_log_path, '执行失败' + step1)

        step2 = "-----step2:备机非事务下执行set语句，不满足10条set语句" \
                "且没有写语句，查看日志;expect:不建立连接-----"
        self.logger.info(step2)
        set_cmd = f'''set search_path to ds, public;
            set current_schema to public;
            show current_schema;'''
        set_msg = self.standby_sh.execut_db_sql(set_cmd)
        self.logger.info(set_msg)
        self.assertEquals(set_msg.count(self.constant.SET_SUCCESS_MSG),
                          2, '执行失败' + step2)
        self.assertEquals('public', set_msg.splitlines()[-2].strip(),
                          '执行失败' + step2)
        time.sleep(2)
        shell_cmd = f"ls -t {self.new_log_path}"
        self.logger.info(shell_cmd)
        shell_msg = self.common.get_sh_result(self.standby_node, shell_cmd)
        logfile = os.path.join(self.new_log_path, shell_msg.split()[-1])
        self.logger.info(logfile)
        shell_cmd = f"cat {logfile}"
        self.logger.info(shell_cmd)
        shell_msg = self.common.get_sh_result(self.standby_node, shell_cmd)
        self.logger.info(shell_msg)
        self.assertNotIn('Connecting to remote server',
                         shell_msg, '执行失败:' + step2)
        self.assertIn('LOG:  libpqsw', shell_msg, '执行失败:' + step2)

        step3 = "-----step3:备机非事务下执行set语句;expect:建立连接，并转发给主机-----"
        self.logger.info(step3)
        set_cmd = f'''set search_path to ds, public;
            set current_schema to public;
            set datestyle to postgres, dmy;
            set time zone 'pst8pdt';
            set time zone 'europe/rome';
            set enable_default_ustore_table to on;
            set cost_param to 1;
            set enable_partitionwise to on;
            set partition_page_estimation to on;
            set enable_functional_dependency to on;'''
        set_msg = self.standby_sh.execut_db_sql(set_cmd)
        self.logger.info(set_msg)
        self.assertEquals(set_msg.count(self.constant.SET_SUCCESS_MSG),
                          10, '执行失败' + step3)
        time.sleep(2)
        shell_cmd = f"ls -t {self.new_log_path}"
        self.logger.info(shell_cmd)
        shell_msg = self.common.get_sh_result(self.standby_node, shell_cmd)
        logfile = os.path.join(self.new_log_path, shell_msg.split()[-1])
        self.logger.info(logfile)
        shell_cmd = f"cat {logfile}"
        self.logger.info(shell_cmd)
        shell_msg = self.common.get_sh_result(self.standby_node, shell_cmd)
        self.logger.info(shell_msg)
        self.assertIn('Connecting to remote server',
                      shell_msg, '执行失败:' + step3)
        self.assertIn('LOG:  libpqsw', shell_msg, '执行失败:' + step3)
        shell_cmd = f"rm -rf {self.new_log_path}"
        self.logger.info(shell_cmd)
        shell_msg = self.common.get_sh_result(self.standby_node, shell_cmd)
        self.assertEquals('', shell_msg, '执行失败:' + step3)
        restart_res = self.standby_sh.restart_db_cluster()
        self.assertTrue(restart_res, '重启失败')

        step4 = "-----step4:执行set语句和1条写语句，查看日志;" \
                "expect:建立连接，并转发给主机-----"
        self.logger.info(step4)
        sql_cmd = f'''set current_schema to public;
            create table {self.table_name}(id int,name varchar(20));'''
        sql_msg = self.standby_sh.execut_db_sql(sql_cmd)
        self.logger.info(sql_msg)
        self.assertIn(self.constant.SET_SUCCESS_MSG,
                      sql_msg, '执行失败' + step4)
        self.assertIn(self.constant.TABLE_CREATE_SUCCESS,
                      sql_msg, '执行失败' + step4)
        time.sleep(2)
        shell_cmd = f"ls -t {self.new_log_path}"
        self.logger.info(shell_cmd)
        shell_msg = self.common.get_sh_result(self.standby_node, shell_cmd)
        logfile = os.path.join(self.new_log_path, shell_msg.split()[-1])
        self.logger.info(logfile)
        shell_cmd = f"cat {logfile}"
        self.logger.info(shell_cmd)
        shell_msg = self.common.get_sh_result(self.standby_node, shell_cmd)
        self.logger.info(shell_msg)
        self.assertIn('we find new transfer request',
                      shell_msg, '执行失败:' + step4)
        self.assertIn('Connecting to remote server',
                      shell_msg, '执行失败:' + step4)
        self.assertIn(f'LOG:  libpqsw', shell_msg, '执行失败:' + step4)

    def tearDown(self):
        step5 = "-----step5:环境清理，恢复参数;expect:环境清理成功，恢复参数成功-----"
        self.logger.info(step5)
        drop_cmd = f"drop table {self.table_name};"
        drop_msg = self.standby_sh.execut_db_sql(drop_cmd)
        self.logger.info(drop_msg)
        result1 = self.standby_sh.execute_gsguc(
            'set', self.constant.GSGUC_SUCCESS_MSG,
            f'{self.enable_remote_execute}={self.remote_execute_default}')
        restart_res = self.standby_sh.restart_db_cluster()
        show_remote_execute = self.common.show_param(self.enable_remote_execute)
        result2 = self.standby_sh.execute_gsguc(
            'reload', self.constant.GSGUC_SUCCESS_MSG,
            f'{self.log_statement}={self.log_statement_default}')
        result3 = self.standby_sh.execute_gsguc(
            'reload', self.constant.GSGUC_SUCCESS_MSG,
            f'{self.log_directory}=\'{self.log_dir_default}\'', single=True)
        show_log_statement = self.common.show_param(self.log_statement)
        show_log_directory = self.common.show_param(self.log_directory)
        self.logger.info("-----断言teardown-----")
        self.assertIn(self.constant.TABLE_DROP_SUCCESS,
                      drop_msg, '执行失败' + step5)
        self.assertTrue(result1, '执行失败' + step5)
        self.assertTrue(restart_res, '执行失败' + step5)
        self.assertEquals(show_remote_execute, self.remote_execute_default,
                          '执行失败' + step5)
        self.assertTrue(result2, '执行失败' + step5)
        self.assertTrue(result3, '执行失败' + step5)
        self.assertEquals(show_log_statement, self.log_statement_default,
                          '执行失败' + step5)
        self.assertEquals(show_log_directory, self.log_dir_default,
                          '执行失败' + step5)
        self.logger.info(f"-----{os.path.basename(__file__)} end-----")
